package com.dbflow5.livedata;

import com.dbflow5.BaseUnitTest;
import com.dbflow5.TestDatabase;
import com.dbflow5.config.FlowManager;
import com.dbflow5.database.DatabaseWrapper;
import com.dbflow5.query.ModelQueriable;
import com.dbflow5.query.SQLite;
import com.dbflow5.structure.Model;
import org.junit.Assert;
import org.junit.Test;

import java.util.List;
import java.util.function.Function;

public class LiveDataTest extends BaseUnitTest {
    @Test
    public void live_data_executes_for_a_few_model_queries() {
        LiveData<List<LiveDataModel>> data = QueryLiveData.toLiveData(SQLite.select().from(LiveDataModel.class), ModelQueriable::queryList);

        data.observeForever( liveDataModels -> {
        });

        List<LiveDataModel> value = data.getValue();
        Assert.assertTrue(value.isEmpty());

        FlowManager.database(TestDatabase.class, testDatabase -> null)
                .beginTransactionAsync((Function<DatabaseWrapper, Object>) db -> {
                    for (int i = 0; i <= 2; i++) {
                        LiveDataModel model = new LiveDataModel(String.valueOf(i), i);
                        Model.insert(LiveDataModel.class, model, db);
                    }
                    return null;
                }).execute(null, null, null, null);

        FlowManager.database(TestDatabase.class, testDatabase -> null).tableObserver().checkForTableUpdates();

        List<LiveDataModel> value2 = data.getValue();
        if (value2.size() != 3) {
            Assert.fail("expected " + value2.size() + " == 3");
        }
        Assert.assertEquals(3, value2.size());
    }
}
